package service

import (
	"time"

	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
)

const (
	FilterRuleFilename = "filter_rule.yml"
)

func ReadFilterRules() []*model.FilterRule {
	rules := make([]*model.FilterRule, 0)
	err := util.ReadYmlFile(util.PathJoin(util.GetWorkDir(), FilterRuleFilename), &rules)
	if err != nil {
		log.Error("read filter rule failed, err=%v", err)
		return nil
	}

	log.Debug("get filter rules success")

	return rules
}

func WriteFilterRule(rule *model.FilterRule) error {
	if rule == nil {
		return nil
	}

	if len(rule.Key) == 0 {
		rule.Key = time.Now().Format(time.DateTime)
	}

	existRules := ReadFilterRules()
	rules := append(existRules, rule)

	err := util.WriteYmlFile(rules, util.PathJoin(util.GetWorkDir(), FilterRuleFilename))
	if err != nil {
		log.Error("write filter rule failed, rule=%v, err=%v", rule, err)
		return err
	}

	log.Debug("add filter rule success, rule=%+v", rule)

	return nil

}
